﻿using Coldairarrow.Business.PB;
using Coldairarrow.Entity.Base;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.PB;
using Coldairarrow.Entity.Print;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.PB
{
    [Route("/PB/[controller]/[action]")]
    public class PB_BuildingnumberController : BaseApiController
    {
        #region DI

        private readonly MongoDBOptions _mongodbOptions;
        public PB_BuildingnumberController(IPB_BuildingnumberBusiness pB_BuildingnumberBus, IOperator op, IOptions<MongoDBOptions> mongodbOptions)
        {
            _pB_BuildingnumberBus = pB_BuildingnumberBus;
            _Op = op;
            _mongodbOptions = mongodbOptions.Value;
        }

        IPB_BuildingnumberBusiness _pB_BuildingnumberBus { get; }
        IOperator _Op { get; }
        #endregion

        #region 获取

        [HttpPost]
        public async Task<PageResult<PB_Buildingnumber>> GetDataList(PageInput<ConditionDTO> input)
        {
            return await _pB_BuildingnumberBus.GetDataListAsync(input);
        }

        [HttpPost]
        public async Task<PB_Buildingnumber> GetTheData(IdInputDTO input)
        {
            return await _pB_BuildingnumberBus.GetTheDataAsync(input.id);
        }
        /// <summary>
        /// 通过项目编号查询楼号
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<PB_BuildingnumberDTO>> GetDataLists(string ProjectId)
        {
            var res = await _pB_BuildingnumberBus.GetDataList(ProjectId);
            return res;
        }
        /// <summary>
        /// 通过项目id楼号id获取楼号详情数据
        /// </summary>
        /// <param name="ProjectId">项目id</param>
        /// <param name="BuildingnumberId">楼号id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PB_Buildingnumber> PB_BuildingnumberDetails(string ProjectId, string BuildingnumberId)
        {
            return await _pB_BuildingnumberBus.PB_BuildingnumberDetails(ProjectId, BuildingnumberId);

        }
        /// <summary>
        /// 获取文本描述集合
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<List<Base_EnumItem>> GetTextList()
        {
            var List = await _pB_BuildingnumberBus.GetTextList();
            return List;
        }
        #endregion

        #region 提交

        [HttpPost]
        public async Task SaveData(PB_Buildingnumber data)
        {
            if (data.Id.IsNullOrEmpty())
            {
                InitEntity(data);

                await _pB_BuildingnumberBus.AddDataAsync(data);
            }
            else
            {
                await _pB_BuildingnumberBus.UpdateDataAsync(data);
            }
        }

        [HttpPost]
        public async Task DeleteData(List<string> ids)
        {
            await _pB_BuildingnumberBus.DeleteDataAsync(ids);
        }


        /// <summary>
        /// 楼号推送消息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<AjaxResult> PushMessage(PB_BuildingnumberTiper data)
        {
            return await _pB_BuildingnumberBus.PushMessage(data, _mongodbOptions);
        }

        /// <summary>
        /// 项目导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<AjaxResult> Import(IFormFile file)
        {
            string ReturnValue = string.Empty;
            //定义一个bool类型的变量用来做验证
            bool flag = true;
            try
            {
                #region 检查文件
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                //定义一个集合一会儿将数据存储进来,全部一次丢到数据库中保存
                var Data = new List<PB_Buildingnumber>();
                List<string> liststr = new List<string>();
                MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                IWorkbook book;
                if (fileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(ms);
                }
                else if (fileExt == ".xls")
                {
                    book = new HSSFWorkbook(ms);
                }
                else
                {
                    book = null;
                }
                ISheet sheet = book.GetSheetAt(0);

                int CountRow = sheet.LastRowNum + 1;//获取总行数

                if (CountRow - 1 == 0)
                {
                    return Error("Excel列表数据项为空!");

                }
                #endregion
                #region 循环验证
                for (int i = 1; i < CountRow; i++)
                {
                    //获取第i行的数据
                    var row = sheet.GetRow(i);
                    if (row != null)
                    {
                        //循环的验证单元格中的数据
                        for (int j = 0; j < 6; j++)
                        {
                            if ((j == 4 || j == 5) || (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0))
                            {
                                //return Error(ReturnValue += $"注意第{i + 1}行,第{j + 1}列数据为空。");
                            }
                            else
                            if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                            {
                                flag = false;
                                return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                            }
                        }
                    }
                }
                #endregion
                if (flag)
                {

                    for (int i = 0; i < CountRow; i++)
                    {
                        if (i != 0)
                        {

                            PB_Buildingnumber buildingnumber = new PB_Buildingnumber();
                            var row = sheet.GetRow(i);
                            if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0)
                            {
                                buildingnumber.Id = IdHelper.GetId();
                                buildingnumber.CreatorId = _Op.UserId;
                                buildingnumber.CreateTime = DateTime.Now;
                                buildingnumber.LiftPlatNums = 0;
                                ; buildingnumber.PlanTime = DateTime.Now;
                                buildingnumber.Deleted = false;
                                buildingnumber.ProjectId = row.GetCell(0).ToString();

                            }
                            if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0)
                            {
                                buildingnumber.Buildingnumber = row.GetCell(1).ToString();
                            }

                            if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0)
                            {

                                buildingnumber.StandsNumber = Convert.ToInt32(row.GetCell(2).ToString());
                            }

                            buildingnumber.CreateTime = DateTime.Now;
                            Data.Add(buildingnumber);
                            liststr.Add(buildingnumber.ProjectId + "," + buildingnumber.Buildingnumber);
                        }


                    }
                    //判断导入的数据是否存在
                    var lists = _pB_BuildingnumberBus.GetQueryableOK<PB_Buildingnumber>().Where(x => liststr.Contains(x.ProjectId + "," + x.Buildingnumber));
                    if (lists.Count() > 0)
                    {
                        return Error(ReturnValue = "导入的数据中有已存在数据库中,请勿重复导入");
                    }
                    //项目管理
                    var listContactsId = Data.Select(s => s.ProjectId).Select(s => s.Trim()).Distinct().ToList();
                    var ProjectId = _pB_BuildingnumberBus.GetQueryableOK<PB_Project>().Where(w => listContactsId.Contains(w.Code)).ToDictionary(k => k.Id, v => v.Code);

                    foreach (var item in Data)
                    {
                        if (ProjectId.ContainsValue(item.ProjectId.Trim()))
                        {
                            item.ProjectId = ProjectId.FirstOrDefault(w => w.Value.Contains(item.ProjectId.Trim())).Key;
                        }
                        else
                        {
                            throw new Exception(item.ProjectId);
                        }
                    }
                    if (Data.Count > 0)
                    {
                        try
                        {
                            await _pB_BuildingnumberBus.AddDataExlAsync(Data);
                        }
                        catch (Exception ex)
                        {
                            string ErrLogCollection = "ErrLog";
                            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                            ErrLog err = new ErrLog()
                            {
                                Name = "楼号导入",
                                Interface = "/PB/PB_Buildingnumber/Import2",
                                Type = "错误",
                                Time = DateTime.Now,
                                Remark = ex.Message
                            };
                            mongo.Add<ErrLog>(ErrLogCollection, err);
                        }
                        ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。";

                    }
                }
                if (!flag)
                {
                    return Error(ReturnValue = "数据存在问题！" + ReturnValue);
                }
            }

            catch (Exception EX)
            {
                ReturnValue = EX.ToString();
                return Error(ReturnValue);
            }
            return Success(ReturnValue);
        }


        [HttpPost]
        public async Task PatrolStatus(string BuildId, bool IsInspection)
        {
            await _pB_BuildingnumberBus.PatrolStatus(BuildId, IsInspection);
        }


        /// <summary>
        /// 项目导入
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [NoCheckJWT]
        public async Task<AjaxResult> Import2(IFormFile file)
        {
            string ReturnValue = string.Empty;
            //定义一个bool类型的变量用来做验证
            bool flag = true;
            try
            {
                #region 检查文件
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                //定义一个集合一会儿将数据存储进来,全部一次丢到数据库中保存
                var Data = new List<PB_Buildingnumber>();
                var liststr = new List<string>();
                MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                IWorkbook book;
                if (fileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(ms);
                }
                else if (fileExt == ".xls")
                {
                    book = new HSSFWorkbook(ms);
                }
                else
                {
                    book = null;
                }
                ISheet sheet = book.GetSheetAt(0);

                int CountRow = sheet.LastRowNum + 1;//获取总行数

                if (CountRow - 1 == 0)
                {
                    return Error("Excel列表数据项为空!");

                }
                #endregion
                #region 循环验证
                for (int i = 1; i < CountRow; i++)
                {
                    //获取第i行的数据
                    var row = sheet.GetRow(i);
                    if (row != null)
                    {
                        //循环的验证单元格中的数据
                        for (int j = 0; j < 6; j++)
                        {
                            if ((j == 4 || j == 5) || (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0))
                            {
                                //return Error(ReturnValue += $"注意第{i + 1}行,第{j + 1}列数据为空。");
                            }
                            else
                            if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                            {
                                flag = false;
                                return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                            }
                        }
                    }
                }
                #endregion
                if (flag)
                {

                    for (int i = 0; i < CountRow; i++)
                    {
                        if (i != 0)
                        {
                            PB_Buildingnumber buildingnumber = new PB_Buildingnumber();
                            var row = sheet.GetRow(i);

                            if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0)
                            {
                                buildingnumber.Id = IdHelper.GetId();
                                buildingnumber.CreatorId = _Op.UserId;
                                buildingnumber.CreateTime = DateTime.Now;
                                buildingnumber.LiftPlatNums = 0;
                                buildingnumber.PlanTime = DateTime.Now;
                                buildingnumber.ProjectId = row.GetCell(0).ToString();
                            }
                            if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0)
                            {
                                buildingnumber.Buildingnumber = row.GetCell(1).ToString();
                            }
                            if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0)
                            {
                                buildingnumber.StandsNumber = Convert.ToInt32(row.GetCell(2).ToString());
                            }
                            else
                            {
                                buildingnumber.StandsNumber = 0;
                            }
                            buildingnumber.CreateTime = DateTime.Now;
                            buildingnumber.Deleted = false;
                            Data.Add(buildingnumber);
                            liststr.Add(buildingnumber.ProjectId + "," + buildingnumber.Buildingnumber);
                        }


                    }

                    //判断导入的数据是否存在
                    var lists = _pB_BuildingnumberBus.GetQueryableOK<PB_Buildingnumber>().Where(x => liststr.Contains(x.ProjectId + "," + x.Buildingnumber));
                    if (lists.Count() > 0)
                    {
                        return Error(ReturnValue = "导入的数据中有已存在数据库中,请勿重复导入");
                    }
                    var listContactsId = Data.Select(s => s.ProjectId).Select(s => s.Trim()).Distinct().ToList();
                    var ProjectId = _pB_BuildingnumberBus.GetQueryableOK<PB_Project>().Where(w => listContactsId.Contains(w.Code)).ToDictionary(k => k.Id, v => v.Code);

                    foreach (var item in Data)
                    {
                        if (ProjectId.ContainsValue(item.ProjectId.Trim()))
                        {
                            item.ProjectId = ProjectId.FirstOrDefault(w => w.Value.Contains(item.ProjectId.Trim())).Key;
                        }
                        else
                        {
                            ///错误信息提示
                            throw new Exception(item.ProjectId);
                        }
                    }

                    if (Data.Count > 0)
                    {
                        try
                        {
                            await _pB_BuildingnumberBus.AddDataExlAsync(Data);
                        }
                        catch (Exception ex)
                        {
                            string ErrLogCollection = "ErrLog";
                            MongoDBHelper mongo = new MongoDBHelper(_mongodbOptions);
                            ErrLog err = new ErrLog()
                            {
                                Name = "楼号导入",
                                Interface = "/PB/PB_Buildingnumber/Import",
                                Type = "错误",
                                Time = DateTime.Now,
                                Remark = ex.Message
                            };
                            mongo.Add<ErrLog>(ErrLogCollection, err);
                        }
                        ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。";

                    }
                }
                if (!flag)
                {
                    return Error(ReturnValue = "数据存在问题！" + ReturnValue);
                }
            }

            catch (Exception EX)
            {
                return Error("数据异常！");
            }
            return Success(ReturnValue);
        }



        /// 楼号信息模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NoCheckJWT]
        public IActionResult ExportToExcel()
        {
            //创建EXCEL工作薄
            IWorkbook workBook = new XSSFWorkbook();
            //创建sheet1文件表
            ISheet sheet = workBook.CreateSheet("楼号信息");
            var expDir = string.Format("{0}Export\\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
                    DateTime.Now.ToString("yyyyMM"));

            if (!Directory.Exists(expDir)) Directory.CreateDirectory(expDir);

            string filePath = string.Format("{0}\\CD{1}.xlsx", expDir, DateTime.Now.ToString("yyyyMMddHHmmss"));

            #region 创建Excel表头(sheet1)
            //创建excel 表头
            IRow header = sheet.CreateRow(0);

            ICell cell = header.CreateCell(0);
            cell.SetCellValue("编号");

            cell = header.CreateCell(1);
            cell.SetCellValue("楼号");


            cell = header.CreateCell(2);
            cell.SetCellValue("机位");


            #endregion

            //工作流写入，通过流的方式进行创建生成文件
            using (MemoryStream stream = new MemoryStream())
            {
                workBook.Write(stream);
                byte[] buffer = stream.ToArray();

                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", string.Format("楼号信息{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss")));
            }

        }
        /// <summary>
        /// 获取当前钉钉用户所管理的项目列表
        /// </summary>
        /// <param name="input"></param>
        /// <param name="DingUserId">用户钉钉号</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<BuildingnumberMenuDto>> GetBulidMenuList(PageInput<IT_LocalDetailDtolistContionDTO> input, string DingUserId)
        {

            var list = await _pB_BuildingnumberBus.GetBulidMenuList(input, DingUserId);
            return list;
        }

        /// <summary>
        /// 获取出差明细统计数据
        /// </summary>
        /// <param name="StartTime">起始日期</param>
        /// <param name="EndTime">结束日期</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<PersonnelListDto>> GetPersonnelList(string StartTime, string EndTime)
        {
            List<PersonnelListDto> ListData = await _pB_BuildingnumberBus.GetPersonnelList(StartTime, EndTime);
            return ListData;
        }


        /// <summary>
        /// 依据月份 天数导出出差明细数据
        /// </summary>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ExportPersonnel(string StartTime, string EndTime)
        {
            List<PersonnelListDto> res = await _pB_BuildingnumberBus.GetPersonnelList(StartTime, EndTime);
            HSSFWorkbook book = new HSSFWorkbook();
            ISheet s1 = book.CreateSheet("出差明细统计表");
            IRow r1 = s1.CreateRow(0);
            r1.CreateCell(0).SetCellValue("序号");
            r1.CreateCell(1).SetCellValue("部门");
            r1.CreateCell(2).SetCellValue("岗位");
            r1.CreateCell(3).SetCellValue("姓名");
            r1.CreateCell(4).SetCellValue("出差地点");
            r1.CreateCell(5).SetCellValue("出差天数");
            r1.CreateCell(6).SetCellValue("项目名称");
            r1.CreateCell(7).SetCellValue("项目地址(详细地址)");
            int index = 1;
            for (int i = 0; i < res.Count; i++)
            {
                IRow rt = s1.CreateRow(i + 1);
                rt.CreateCell(0).SetCellValue(index);
                rt.CreateCell(1).SetCellValue(res[i].DepartmentName);
                rt.CreateCell(2).SetCellValue(res[i].UserPost);
                rt.CreateCell(3).SetCellValue(res[i].RealName);
                rt.CreateCell(4).SetCellValue(res[i].RName + res[i].RsName);
                rt.CreateCell(5).SetCellValue(Convert.ToDouble(res[i].Days.ToString()));
                rt.CreateCell(6).SetCellValue(res[i].ProjectName);
                rt.CreateCell(7).SetCellValue(res[i].Address);
                index++;
            }
            var expDir = string.Format("{0}Export\\{1}", System.AppDomain.CurrentDomain.BaseDirectory,
                  DateTime.Now.ToString("yyyyMM"));
            if (!Directory.Exists(expDir)) Directory.CreateDirectory(expDir);
            string filePath = string.Format("{0}\\CD{1}.xlsx", expDir, DateTime.Now.ToString("yyyyMMddHHmmss"));
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            string fileName = "出差明细统计表.xlsx";
            //把Excel转为流，输出
            //创建文件流
            System.IO.MemoryStream bookStream = new System.IO.MemoryStream();
            //将工作薄写入文件流
            book.Write(bookStream);

            //输出之前调用Seek（偏移量，游标位置) 把0位置指定为开始位置
            bookStream.Seek(0, System.IO.SeekOrigin.Begin);
            //Stream对象,文件类型,文件名称
            return File(bookStream, "application/vnd.ms-excel", fileName);
        }

        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="DingUserId">钉钉id</param>
        /// <returns></returns>
        [HttpPost]
      public  async Task<PageResult<BuildingnumberMenuDto>> GetBulidMenuListS(PageInput<IT_LocalDetailDtolistContionDTO> input, string DingUserId) {
            var list = await _pB_BuildingnumberBus.GetBulidMenuListS(input, DingUserId);
            return list;
        }
        /// <summary>
        /// 获取最新的一条项目进度信息
        /// </summary>
        /// <param name="ProjectId">项目id</param>
        /// <param name="Bulid">楼号id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PB_ProjectStatuLoDto> GetArticle1(string ProjectId, string Bulid)
        {
            //创建实体
            PB_ProjectStatuLoDto data = new PB_ProjectStatuLoDto();
            data = await _pB_BuildingnumberBus.GetArticle1(ProjectId,Bulid);
            return data;
        }

        /// <summary>
        /// 传入项目id楼号id验证今日是否进行进度记录
        /// </summary>
        /// <param name="ProjectId">项目id</param>
        /// <param name="Bulid">楼号id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> Result(string ProjectId, string Bulid) {
         return   await _pB_BuildingnumberBus.Result(ProjectId,Bulid);
        }

        /// <summary>
        /// 传入楼号id判断是否进行协作记录
        /// </summary>
        /// <param name="Bulid"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> ResultTime(string Bulid) {
            return await _pB_BuildingnumberBus.ResultTime(Bulid);
        }

        /// <summary>
        /// 获取用户树状列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<BaseTreeDto>> GetBaseTreeListAsyncs() {
            List < BaseTreeDto  > ListData= await _pB_BuildingnumberBus.GetBaseTreeListAsyncs();
            return ListData;
        }

        /// <summary>
        /// 移除操作
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task Transfer(BuildingnumberTransfer data) {
             await _pB_BuildingnumberBus.Transfer(data);
        }
        /// <summary>
        /// 钉钉维护楼号起始层终止层
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task UpdateBuliNo(UpdateBuliNo data) {
             await _pB_BuildingnumberBus.UpdateBuliNo(data);
        }

        /// <summary>
        /// 钉钉查看
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<GetMaterialSummary>> GetMaterialSummary(PageInput<ProjectReturnConditionDTO> input) {
            var res = await _pB_BuildingnumberBus.GetMaterialSummary(input);
            return res;
        }
        #endregion
    }
}